/*
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.chimos.property.compiler.passtwo.javafx;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Map;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.util.CheckClassAdapter;

import de.chimos.property.compiler.Config;
import de.chimos.property.compiler.PropertyInfo;

/**
 * @author Niklas Hofmann
 */
public class PassTwoJFXFileVisitor extends SimpleFileVisitor<Path> {

    private final Map<String, Map<String, PropertyInfo>> properties;
    
    private final Config config;
    
    public PassTwoJFXFileVisitor(Map<String, Map<String, PropertyInfo>> properties, Config config)
    {
        this.properties = properties;
        
        this.config = config;
    }
    
    @Override
    public FileVisitResult visitFile(Path t, BasicFileAttributes bfa) throws IOException {
        
        if(t.getFileName().toString().endsWith(".class"))
        {
            ClassWriter cw = new ClassWriter(0);
            CheckClassAdapter cca = new CheckClassAdapter(cw, true);
            ClassReader cr = new ClassReader(new FileInputStream(t.toFile()));
            cr.accept(new PassTwoJFXClassVisitor(properties, cca, config), 0);

            t.toFile().delete();

            try(FileOutputStream o = new FileOutputStream(t.toFile()))
            {
                o.write(cw.toByteArray());
            }
        }
        
        return FileVisitResult.CONTINUE;
    }
    
}
